﻿//
// Created by QU on 24-9-28.
//

#ifndef WORKER_H
#define WORKER_H

#include <string>
#include <map>
#include <mutex>
#include <thread>
#include <stop_token>
#include <atomic>
#include <optional>
#include <vector>

#include <boost/asio.hpp>

#include "server/server/Session.h"

namespace asio = boost::asio;
namespace ip = asio::ip;

using tcp = ip::tcp;

class Worker
{
public:
    using SessionMap = std::map<std::string, std::shared_ptr<Session>>;

    explicit Worker(asio::io_context& io_context, std::stop_token worker_stop_token);
    ~Worker();

    void start();
    void forceStop();

    void addSession(const std::string& uuid, std::shared_ptr<Session> session);
    void clearSession(const std::string& uuid);
    void clearAllSessions();

    [[nodiscard]] asio::io_context& getIOContext() const;
    [[nodiscard]] std::shared_ptr<std::stop_source> getSharedSessionStopSource() const;

    std::optional<std::shared_ptr<Session>> getSession(const std::string& session_uuid);
    [[nodiscard]] size_t getSessionCount() const;
    [[nodiscard]] std::vector<std::shared_ptr<Session>> getAllSessions() const;

    [[nodiscard]] bool isWorking() const;

private:
    asio::io_context& m_io_context;
    asio::executor_work_guard<asio::io_context::executor_type> m_worker_work_guard;
    std::stop_token m_worker_stop_token;

    SessionMap m_sessions_map;
    std::shared_ptr<std::stop_source> m_shared_session_stop_source;

    std::jthread m_worker_thread;
    std::atomic<bool> m_is_working;
    mutable std::mutex m_mutex;
};

#endif //WORKER_H
